package org.abio.XasML.rpc
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
	
	import mx.core.mx_internal;
	
	import org.abio.XasML.reflect.ClassInfo;

	public class ClassLoader extends Proxy
	{
		static private const loaderDict:Dictionary=new Dictionary();
		private var url:String=null;

		public function ClassLoader(url:String)
		{
			this.url=url;
			if(ClassLoader.loaderDict.hasOwnProperty(url)==false){
				ClassLoader.loaderDict[url]=new Loader();
				(ClassLoader.loaderDict[url] as Loader).load(new URLRequest(url));
			}
		}
		
		override flash_proxy function getProperty(name:*):*
		{
			return function delayedCall(...args):AsyncResult{
				var result:AsyncResult=new AsyncResult();
				if((ClassLoader.loaderDict[url] as Loader).content==null){
					(ClassLoader.loaderDict[url] as Loader).contentLoaderInfo.addEventListener(Event.COMPLETE, function COMPLETE(e:Event):void{
						var tempClass:Class=(ClassLoader.loaderDict[url] as Loader).contentLoaderInfo.applicationDomain.getDefinition(name) as Class;
						var tempDomain:ApplicationDomain=(ClassLoader.loaderDict[url] as Loader).contentLoaderInfo.applicationDomain;
						result.mx_internal::applyResult(ClassInfo.of(tempClass));
					});				
				}else{
					delayedCall(1, function DELAYEDCALL():void{
						var tempClass:Class=(ClassLoader.loaderDict[url] as Loader).contentLoaderInfo.applicationDomain.getDefinition(name) as Class;
						var tempDomain:ApplicationDomain=(ClassLoader.loaderDict[url] as Loader).contentLoaderInfo.applicationDomain;
						result.mx_internal::applyResult(ClassInfo.of(tempClass));
					});
				}
				return result;
			}
		}
	}
}